import React from 'react';
import { Form, Card, Button, Tag, message, Popconfirm, Radio } from 'antd';
import { history } from 'umi'
import { get as getPath } from 'object-path';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { BottomAction } from '@/components';
import { hasWorkFlowByType } from '@/pages/WorkFlow/utils';
import pageTabUtil from '@/utils/pageTabUtil';

// import OrganizationSelect from '@/components/OrganizationSelect';
import LimitInput from '@/components/LimitInput';
import { TreeSelectGroup } from '@/pages/Setting/Privilege/components/TreeSelectGroupRoleForPrivilege';
import { getManageListAuth_AllData } from '@/pages/Setting/Privilege/services';
import { useRequest } from '@/hooks';
import { BaseWrapper } from '../components';
import { addDuty, getDutyDetail2, updateDuty } from '../services';
import { AUDIT } from '../constant';
import styles from './index.less';

const PostEdit = ({ form, location }) => {
    const { query } = location;
    const { getFieldDecorator } = form;
    const [loading, setLoading] = React.useState(false);
    const [submitLoading, setSubmitLoading] = React.useState(false);
    const [info, setInfo] = React.useState(null);

    const { data: manageList } = useRequest(getManageListAuth_AllData);

    const isAddPage = React.useMemo(() => {
        const { pathname = '' } = location;
        return pathname.includes('postadd');
    }, [location]);

    const getDetail = async () => {
        setLoading(true);

        const params = { dutyCode: query?.dutyCode };
        const res = await getDutyDetail2(params);
        setLoading(false);
        const { data, code, msg } = res;
        if (code === 10000) {
            setInfo(data);
        } else {
            message.error(msg);
        }
    };

    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                setSubmitLoading(true);
                // 流程不存在提示
                const { workFlowUrl } = await hasWorkFlowByType('PostChange');
                if (!workFlowUrl) {
                    setSubmitLoading(false);
                    return;
                }
                if (isAddPage) {
                    addDuty({
                        ...values,
                        organizationCode: query && query.organizationCode,
                        organizationName: query && query.organizationName
                    })
                        .then(res => {
                            const { code, data: id, msg } = res;
                            if (code === 10000) {
                                history.push(`${workFlowUrl}${id}`);
                            } else {
                                message.error(msg);
                            }
                        })
                        .finally(() => {
                            setSubmitLoading(false);
                        });
                } else {
                    updateDuty({
                        ...values,
                        dutyCode: getPath(info, 'dutyCode', '') || (query && query.dutyCode),
                        organizationName: getPath(info, 'organizationName', '')
                    })
                        .then(res => {
                            const { code, data: id, msg } = res;
                            if (code === 10000) {
                                history.push(`${workFlowUrl}${id}`);
                            } else {
                                message.error(msg);
                            }
                        })
                        .finally(() => {
                            setSubmitLoading(false);
                        });
                }
            }
        });
    };
    React.useEffect(() => {
        if (!isAddPage) {
            getDetail();
        }
    }, [isAddPage]);
    return (
        <PageHeaderWrapper>
            <Card
                title={
                    isAddPage ? (
                        '新增岗位'
                    ) : (
                        <>
                            岗位信息
                            {getPath(info, 'auditStatus', '') !== '' && getPath(info, 'auditStatus', '') !== 2 && (
                                <Tag color="orange" style={{ marginLeft: 10 }}>
                                    {AUDIT[getPath(info, 'auditStatus', '')]}
                                </Tag>
                            )}
                        </>
                    )
                }
                bordered={false}
                loading={loading}
                extra={
                    <BottomAction>
                        <Popconfirm
                            title={
                                <>
                                    取消后系统不会保存您填写的信息，
                                    <br />
                                    确认是否要取消？
                                </>
                            }
                            arrowPointAtCenter
                            onConfirm={() => {
                                pageTabUtil.goBack();
                            }}
                            okText="是"
                            cancelText="否"
                        >
                            <Button style={{ marginRight: 8 }}>取消</Button>
                        </Popconfirm>
                        <Button
                            type="primary"
                            disabled={getPath(info, 'auditStatus', '') !== '' && getPath(info, 'auditStatus', '') !== 2}
                            onClick={handleSubmit}
                            loading={submitLoading}
                        >
                            下一步
                        </Button>
                    </BottomAction>
                }
            >
                <BaseWrapper title="基本信息" className={styles.formWrap}>
                    <Form>
                        <Form.Item label="所属机构">
                            {isAddPage ? getPath(query, 'organizationName', '') : getPath(info, 'organizationName', '')}
                        </Form.Item>
                        <Form.Item label="岗位名称(中文)">
                            {getFieldDecorator('dutyAlias', {
                                initialValue: getPath(info, 'dutyAlias', ''),
                                rules: [
                                    {
                                        required: true,
                                        message: '岗位名称(中文)不能为空',
                                        whitespace: true
                                    },
                                    {
                                        max: 100,
                                        message: '岗位名称(中文)最多输入100个字符'
                                    },
                                    {
                                        validator(_, value, callback) {
                                            if (value.indexOf('/') > -1) {
                                                callback('不允许输入:或/');
                                            } else if (value.indexOf(':') > -1) {
                                                callback('不允许输入:或/');
                                            } else {
                                                callback();
                                            }
                                        }
                                    }
                                ]
                            })(<LimitInput maxLength={100} placeholder="请输入岗位名称(中文)" allowClear />)}
                        </Form.Item>
                        <Form.Item label="岗位名称(英文)">
                            {getFieldDecorator('dutyAliasEnglish', {
                                initialValue: getPath(info, 'dutyAliasEnglish', ''),
                                rules: [
                                    {
                                        validator(_, value, callback) {
                                            if (value.indexOf('/') > -1 || value.indexOf(':') > -1) {
                                                callback('不允许输入:或/');
                                            } else {
                                                callback();
                                            }
                                        }
                                    },
                                    {
                                        max: 100,
                                        message: '岗位名称(英文)最多输入100个字符'
                                    }
                                ]
                            })(<LimitInput maxLength={100} placeholder="请输入岗位名称(英文)" allowClear />)}
                        </Form.Item>
                        <Form.Item label="是否主管">
                            {getFieldDecorator('leaderPositionFlag', {
                                initialValue: getPath(info, 'leaderPositionFlag', ''),
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择'
                                    }
                                ]
                            })(
                                <Radio.Group disabled={!isAddPage}>
                                    <Radio value={1}>是</Radio>
                                    <Radio value={0}>否</Radio>
                                </Radio.Group>
                            )}
                        </Form.Item>

                        <Form.Item label="岗位职责(中文)">
                            {getFieldDecorator('dutyDesc', {
                                initialValue: getPath(info, 'dutyDesc', ''),
                                rules: [
                                    {
                                        max: 10000,
                                        message: '岗位职责(中文)最多输入10000个字符'
                                    }
                                ]
                            })(
                                <LimitInput
                                    area
                                    maxLength={10000}
                                    placeholder="请输入岗位职责(中文)"
                                    autosize={{ minRows: 3, maxRows: 6 }}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="岗位职责(英文)">
                            {getFieldDecorator('dutyDescEnglish', {
                                initialValue: getPath(info, 'dutyDescEnglish', ''),
                                rules: [
                                    {
                                        max: 20000,
                                        message: '岗位职责(英文)最多输入20000个字符'
                                    }
                                ]
                            })(
                                <LimitInput
                                    area
                                    maxLength={20000}
                                    placeholder="请输入岗位职责(英文)"
                                    autosize={{ minRows: 3, maxRows: 6 }}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="权限模板">
                            {getFieldDecorator('roleCodeList', {
                                initialValue: info?.roleCodeList,
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择'
                                    }
                                ]
                            })(<TreeSelectGroup data={manageList} placeholder="请选择" />)}
                        </Form.Item>
                    </Form>
                </BaseWrapper>
            </Card>
        </PageHeaderWrapper>
    );
};

export default Form.create({})(PostEdit);
